package com.hifar.handler;

import com.hifar.sys.BusiResponse;
import org.apache.logging.log4j.core.config.Order;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.Map;

@ControllerAdvice
@ResponseBody
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ExceptionControllerAdvice {


	@ExceptionHandler({MethodArgumentNotValidException.class})
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public BusiResponse handleValidateException(MethodArgumentNotValidException e) {
		BindingResult bindingResult = e.getBindingResult();
		StringBuilder errBuilder = new StringBuilder();
		bindingResult.getAllErrors().forEach((error) -> {
			FieldError fieldError = (FieldError) error;
			errBuilder.append(fieldError.getDefaultMessage()).append(";");
		});
		return BusiResponse.error(400,errBuilder.toString());
	}

	@ExceptionHandler({Exception.class})
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public BusiResponse handleAllException(Exception errors) {
		errors.printStackTrace();
		return BusiResponse.error(500,errors.getMessage());
	}
}
